<template>
	<view class="bg-or">
		<!-- 顶部问诊状态 -->
		<view class="flex-direction-row justify-between align-center padding-tb-xsm padding-lr-sm bg-consultation"
			:class="{'filter-gray':details.consultationStatus>=2}">
			<!-- 问诊状态(0待问诊、1咨询中、2问诊结束、3取消) -->
			<view class="flex-direction-row align-center">
				<text class="text-xsl iconfont color-df">&#xe653;</text>
				<text
					class="text-df color-df margin-left-xs">{{consultationArr[details.consultationStatus]}}-{{statusArr[details.status]}}</text>
			</view>
			<view class="padding-tb-xs padding-lr radius-sl bg-df" @click="stop">
				<text class="text-smd color-white">结束问诊</text>
			</view>
		</view>
		<!-- <view style="height: 100rpx;"></view> -->
		<scroll-view scroll-y="true" class="" :scroll-into-view="pageToId" :style="{'height': scrollHeight}">
			<!-- 病情卡片 -->
			<view class="bg-white radius-xl padding margin">
				<view class="flex-direction-row justify-between align-center">
					<text class="text-df text-bold">{{details.department}}</text>
					<view class="flex-direction-row align-center"
						@click="$navigator('/pages/hall/patientData?prescriptionCondition='+JSON.stringify(details.prescriptionCondition))">
						<text class="text-smd color-black">患者资料</text>
						<text class="text-xs iconfont color-black-q margin-left-xs">&#xe61f;</text>
					</view>
				</view>
				<view class="flex-direction-column border-top padding-top margin-top">
					<text class="text-df">病情描述：</text>
					<text
						class="text-smd color-black margin-top-xss">{{details.prescriptionCondition?.patientDescription}}</text>
				</view>
			</view>
			<!-- 已选药品 -->
			<view class="bg-white radius-xl padding margin">
				<text class="text-df text-bold">已选药品</text>
				<block v-for='(item,index) in details?.prescriptionProductItemList' :key='index'>
					<view class="flex-direction-row margin-top-sm">
						<image :src="item.imageUrl || '/static/logo.png'" class="cu-photo flex-shrink radius"></image>
						<view class="flex-direction-column flex-sub margin-lr">
							<view class="flex-direction-column flex-sub">
								<text class="text-df color-black">{{item.productName}}</text>
								<text class="text-xsm margin-top-xs color-black-b">规格：{{item.productSpaceName}}</text>
							</view>
							<view class="flex-direction-row align-center justify-between">
								<view class="flex-direction-row align-center">
									<text class="text-smd color-df">￥</text>
									<text class="text-smd color-df text-bold">{{item.price}}</text>
								</view>
								<text class="text-sm color-black-b">x{{item.count}}</text>
							</view>
						</view>
					</view>
				</block>
			</view>
			<!-- 患者情况 -->
			<!-- <view class="bg-white radius-xl padding margin">
				<view class="padding-bottom-sm">
					<text class="text-df text-bold">患者情况</text>
				</view>
				<view class="flex-direction-row justify-between align-center padding-tb-sm">
					<text class="text-smd color-black">患者信息</text>
					<text class="text-smd color-black">{{details.prescriptionCondition?.prescriptionPatient?.name}}
						{{details.prescriptionCondition?.prescriptionPatient?.gender===1?'男':'女'}}
						{{details.prescriptionCondition?.prescriptionPatient?.age}}岁</text>
				</view>
				<view class="flex-direction-row justify-between align-center padding-tb-sm">
					<text class="text-smd color-black">所患疾病</text>
					<text class="text-smd color-black">{{details.prescriptionCondition?.diseasesSuffered}}</text>
				</view>
				<view class="flex-direction-row justify-between align-center padding-tb-sm">
					<text class="text-smd color-black">肝功能</text>
					<text
						class="text-smd color-black">{{liverArr[details.prescriptionCondition?.liverFunction]}}</text>
				</view>
				<view class="flex-direction-row justify-between align-center padding-tb-sm">
					<text class="text-smd color-black">肾功能</text>
					<text
						class="text-smd color-black">{{kidneyArr[details.prescriptionCondition?.renalFunction]}}</text>
				</view>
				<view class="flex-direction-row justify-between align-center padding-tb-sm">
					<text class="text-smd color-black">过敏史</text>
					<text
						class="text-smd color-black">{{allergyArr[details.prescriptionCondition?.allergyHistory]}}</text>
				</view>
				<view class="flex-direction-row justify-between align-center padding-tb-sm">
					<text class="text-smd color-black">生育计划或状态</text>
					<text
						class="text-smd color-black">{{marriageArr[details.prescriptionCondition?.familyPlan]}}</text>
				</view>
			</view> -->
			<!-- v-if="details.prescriptionCondition?.patientImage" -->
			<view class="flex-direction-row align-center justify-center margin-tb">
				<!-- 查看原始处方 -->
				<template v-if="details.prescriptionCondition?.patientImage">
					<view class="border-df padding-lr-xl padding-tb-sm radius-sl margin-right-xl"
						@click="$navigator('/pages/prescription/original?patientImage='+details.prescriptionCondition?.patientImage)">
						<text class="text-df color-df">查看原始处方</text>
					</view>
				</template>
				<!-- 查看处方 -->
				<!-- 以开方 可查看处方 -->
				<template v-if="details.status == 4">
					<view class="bg-df padding-lr-xl padding-tb-sm radius-sl"
						@click="$navigator('/pages/prescription/prescription?id='+optionId)">
						<text class="text-df color-white">查看处方</text>
					</view>
				</template>
				<!-- 去开方 -->
				<template v-else>
					<view class="bg-df padding-lr-xl padding-tb-sm radius-sl" @click="prescribing()">
						<text class="text-df color-white">开处方</text>
					</view>
				</template>
			</view>
			<!-- 消息列表 -->
			<view class="border-top padding-tb-xl text-center">
				<text class="text-df color-black-b">问诊已经开始，本次问诊可持续24小时</text>
			</view>
			<view class="padding">
				<block v-for='(item,index) in messageList' :key='index'>
					<chat :item="item" :showtime="showTime(index)"></chat>
				</block>
			</view>
			<!-- scroll-view底部，已供页面滚动到最后 -->
			<view class="padding-xs" id="scrollId"></view>
		</scroll-view>
		<!-- 底部聊天框 -->
		<!-- 问诊结束，即可不需要聊天框 -->
		<view class="padding flex-direction-row bg-white align-center border-top" v-if="details.consultationStatus < 2">
			<textarea type="text" v-model="message" placeholder="请回复患者～" class="flex-sub padding-sm radius bg-gray"
				auto-height :show-confirm-bar="false" :disable-default-padding="true" cursor-spacing="20"
				:adjust-position="false" @focus="getInput" @blur="outInput" maxlength="100"></textarea>
			<text class="text-sl iconfont color-green padding-left" @click="sendMessage">&#xe607;</text>
		</view>
		<!-- 结束问诊popup -->
		<uni-popup ref="stopPopup" type="center">
			<view class="bg-white radius-xl overflow-hidden" style="width: 660rpx; z-index: 1000;">
				<view class="padding-tb-xsm bg-df text-center">
					<text class="text-lg color-white">结束问诊提示</text>
				</view>
				<view class="padding-tb-xl text-center">
					<text class="text-lg color-black">确认结束此问诊吗？</text>
				</view>
				<view class="flex-direction-row justify-around padding-tb border-top">
					<view class="border-gray radius-sl text-center padding-tb-xs" style="width: 200rpx;"
						@click="closePopup">
						<text class="text-df color-black-q">取消</text>
					</view>
					<view class="border-df radius-sl text-center padding-tb-xs" style="width: 200rpx;"
						@click="closeMsg">
						<text class="text-df color-df">确定</text>
					</view>
				</view>
			</view>
			<view class="" style="height: 200rpx;"></view>
		</uni-popup>
	</view>
</template>

<script>
	let T;
	const windowHeight = uni.getSystemInfoSync().windowHeight;
	import {
		getChatTime
	} from '@/common/tools.js';
	import chat from "@/components/chatItem.vue"
	export default {
		onLoad(option) {
			// 获取窗口高度
			this.scrollHeight = windowHeight + 'px';
			console.log('this.scrollHeight: ', this.scrollHeight);
			// console.log(this.scrollHeight);
			uni.onKeyboardHeightChange(res => {
				console.log(res.height)
				if (res.height) {
					this.scrollHeight = windowHeight - 130 - res.height + 'px';
					// this.scrollHeight = windowHeight - res.height + 20 + 'px'
					// this.popupHeight = '0rpx'
				} else {
					this.scrollHeight = windowHeight - 140 + 'px';
				}
				// this.pageToBottom();
				console.log('this.scrollHeight: ', this.scrollHeight);
				this.$forceUpdate()
			})
			if (option.id) {
				this.optionId = option.id
				console.log('this.optionId: ', this.optionId);
				// 获取处方基本信息
				this.getDetail();
				// 获取聊天数据
				this.getMessage();
				// 定时请求消息列表
				T = setInterval(() => {
					// console.log('22222: ', 22222);
					this.getMessage();
				}, 5000);
			}
			// 监听开处方页面consultation成功返回，并重启请求页面数据
			uni.$on('updateSavePrescription', data => {
				// 获取处方基本信息
				this.getDetail();
			})
		},
		onUnload() {
			uni.$off('updateSavePrescription');
			clearInterval(T);
		},
		components: {
			chat
		},
		data() {
			return {
				consultationStatus: 0,
				details: [],
				messageList: [],
				chargebackIndex: 0,
				statusArr: ['待接诊', '待开方', '已审核', '已复核', '已开方'],
				consultationArr: ['待问诊', '咨询中', '问诊结束', '取消'],
				liverArr: ['正常', '异常', '不清楚'],
				kidneyArr: ['正常', '异常', '不清楚'],
				allergyArr: ['无', '有', '不清楚'],
				marriageArr: ['无', '准备期', '怀孕期', '不清楚'],
				message: '',
				cursorSpacing: 0,
				scrollHeight: '',
				pageToId: ''
			}
		},
		methods: {
			async getDetail() {
				const res = await uni.$request.get('/doctorPrescriptionApi/' + this.optionId, {});
				console.log('getDetail res: ', res.data);
				if (res.code === 200) {
					this.details = res.data;
					if (this.details.consultationStatus < 2) {
						// 状态==沟通中的情况，才会出现底部聊天框
						this.scrollHeight = windowHeight - 140 + 'px';
						console.log('getDetail this.scrollHeight: ', this.scrollHeight);
					}
				} else {
					uni.showModal({
						title: '提示',
						content: '数据查询失败',
						showCancel: false
					});
				}
			},
			async getMessage() {
				const res = await uni.$request.post('/prescriptionMsgApi/list', {
					'prescriptionId': this.optionId,
					'pageSize': 50,
					'orderByColumn': 'create_time',
					'isAsc': 'asc',
				}, {
					// 不显示loading
					showLoading: false
				});
				// console.log('getMessage res: ', res.rows);
				if (res.code === 200) {
					this.messageList = res.rows;

					// 让消息滚到最后一个
					this.pageToBottom();
				} else {
					uni.showModal({
						title: '提示',
						content: '数据查询失败',
						showCancel: false
					});
				}
			},
			// 定时请求消息
			settime() {
				let T = setInterval(() => {
					// console.log('22222: ', 22222);
					this.getMessage();
				}, 5000);
			},
			// 输入框获取焦点
			getInput(e) {

			},
			// 去开处方
			prescribing() {
				// 需要带上患者信息和处方信息
				let data = {
					id: this.details.id,
					prescriptionCode: this.details.prescriptionCode,
					createTime: this.details.prescriptionCondition?.createTime,
					name: this.details.prescriptionCondition?.prescriptionPatient?.name,
					gender: this.details.prescriptionCondition?.prescriptionPatient?.gender,
					age: this.details.prescriptionCondition?.prescriptionPatient?.age,
					prescriptionProductItemList: this.details?.prescriptionProductItemList,
					storeId: this.details.storeId
				}
				uni.navigateTo({
					url: '/pages/prescription/prescribing?prescribingData=' + JSON.stringify(data)
				});
			},
			// 输入框失去焦点
			outInput() {
				this.keyHeight = 0;
			},
			// list组件回到底部
			pageToBottom() {
				this.$nextTick(() => {
					this.pageToId = 'scrollId'
				})
			},
			// 处理消息时间
			showTime(index) {
				let time2 = index === 0 ? 0 : this.messageList[index - 1].createTime;
				return getChatTime(this.messageList[index].createTime, time2);
			},
			// 发消息
			async sendMessage() {
				if (!this.message) return;
				const res = await uni.$request.post('/prescriptionMsgApi', {
					prescriptionId: this.optionId,
					content: this.message,
					type: 1
				});
				// console.log('sendMessage res: ', res.data);
				if (res.code === 200) {
					// 发送消息之后，需要清空输入框
					this.message = ''
					this.getMessage();
				} else {
					uni.showModal({
						title: '提示',
						content: '消息发送失败',
						showCancel: false
					});
				}
			},
			stop() {
				if (this.details.consultationStatus < 2) {
					this.$refs.stopPopup.open();
				}
			},
			closePopup() {
				this.$refs.stopPopup.close();
				// this.$refs.originalPopup.close();
			},
			// 确认结束问诊
			async closeMsg() {
				// /prescriptionMsgApi/closeMsg
				const res = await uni.$request.post('/prescriptionMsgApi/closeMsg', {
					prescriptionId: this.optionId,
				});
				console.log('closeMsg res: ', res.data);
				if (res.code === 200) {
					this.getDetail();
					// 通知其它页面更改结束问诊的状态
					// uni.$emit('updateConsultationStatus',{
					// 	consultationStatus:2
					// })
				} else {
					uni.showModal({
						title: '提示',
						content: '结束问诊失败',
						showCancel: false
					});
				}
				this.$refs.stopPopup.close();
			}
		}
	}
</script>

<style scoped>
	.bg-consultation {
		background-color: #f4e5e2;
	}
</style>